import * as types from './types';
import http from '../utils/https';

const initState = {
  resMessage:{},
  postValue: {},
  delectMessage:{},
  updateMessage: {}
}

// 不要定义到initState里面会被清掉。
let typeString = null;
let _cacheData = null;
export function resMessage(state=initState,action) {
  switch (action.type) {
    case types['ACTION_UPDATE_SUCCESS']:
      return {
        ...state,
        resMessage: action.payload,
        updateMessage: action.update,
      }
    case types['ACTION_'+typeString+'_SUCCESS']:
      return {
        resMessage:action.payload,
        postValue: _cacheData,
        delectMessage: action.delect
      }
    case types['ACTION_'+typeString+'_ERROR']:
      return {
        resMessage:action.payload
      }
    default:
      return state;
  }
}

function errMessage(string, msg) {
  return {
    type: types['ACTION_'+string+'_ERROR'],
    payload: msg,
  }
}

function sucessMessage(string,data,res) {
  return {
    type: types['ACTION_'+string+'_SUCCESS'],
    payload: data,
    delect: string  === 'DELECT' ? res : void 0,
    update: string === 'UPDATE' ? res : void 0
  }
}

export function delect(tableName, data) {
 return async dispatch => {
   const res = await http.post(`/api/form/delect/${tableName}`, data);
   if(res.data.code === types.SUCCESS_CODE && res.status === types.RES_STATUS) {
    typeString = 'DELECT';
    dispatch(sucessMessage(typeString, res.data, res.data.delect))
  } else {
    dispatch(errMessage(typeString, res))
  }
 } 
}

export function update(tableName, data) {
  return async dispatch => {
    const res = await http.post(`/api/form/update/${tableName}`, data);
    if(res.data.code === types.SUCCESS_CODE && res.status === types.RES_STATUS) {
      typeString = 'UPDATE';
      dispatch(sucessMessage(typeString, res.data, res.data.update))
    } else {
      dispatch(errMessage(typeString, res))
    }
  }
}

// 把要发送的数据拿到 需要在给选择条数的时候用
export function search(tableName,data) {
  _cacheData = data;
  return async dispatch => {
    const res = await http.post(`/api/form/search/${tableName}`, data);
    if (res.data.code === types.SUCCESS_CODE && res.status === types.RES_STATUS) {
      typeString = 'SEARCH';
      dispatch(sucessMessage(typeString,res.data))
    } else {
      dispatch(errMessage(typeString,res))
    }
  }
}


export function insert(tableName,data) {
  return async dispatch => {
    const res =  await http.post(`/api/form/add/${tableName}`,data)
    if (res.data.code === types.SUCCESS_CODE && res.status === types.RES_STATUS) {
      typeString = 'INSERT';
      dispatch(sucessMessage(typeString,res.data))
    } else {
      dispatch(errMessage(typeString,res))
    }
  }
}